package com.smartalarmclock.Logic;

import java.util.Iterator;
import java.util.Set;

import com.smartalarmclock.Model.Exceptions.InvalidDeleteDataEntityOperationException;
import com.smartalarmclock.Model.Exceptions.InvalidSaveDataEntityOperationException;
import com.smartalarmclock.Model.*;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
//import android.provider.Settings.Global;
import android.util.Log;

/**
 * AcSyncService - Runs in the background and syncs between the phone contacts and the application.
 * @author elad
 *
 */
public class AcSyncService extends IntentService {
	public AcSyncService() {
		super("AcSyncService");
		Log.d("acSyncService", "in constructor");
	}

	/**
	 * Sleep interval in seconds between iterations
	 */
	protected final int c_SleepInterval = 10;
	
/*
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}
*/
	protected void SyncContacts(Context i_Context) {
		Log.d(getPackageName(), "Syncing contacts");
		SyncAlarmClockToPhone(i_Context);
		SyncPhoneToAlarmClock(i_Context);
	}
	
	/**
	 * Scans the alarm clock contacts to check if any of them was removed.
	 */
	protected void SyncAlarmClockToPhone(Context i_Context) {
		ContactFactory contactFactory = new ContactFactory();
		Set<ISingleContact> alarmclockContacts = contactFactory.GetAllSingleContacts(i_Context);
		Iterator<ISingleContact> contactsIterator = alarmclockContacts.iterator();
		ISingleContact currentContact;
		String[] projection = new String[] { Contacts.LOOKUP_KEY };
		ContentResolver cr = i_Context.getContentResolver();
		
		Cursor phoneContact; 
		
		while (contactsIterator.hasNext()) {
			currentContact = contactsIterator.next();
			
			phoneContact = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, 
					Contacts.LOOKUP_KEY + " = '" + currentContact.GetPhoneContactId() + "'", null, null);
			if (!phoneContact.moveToNext()) {
				try {
					currentContact.Delete(getApplicationContext());
				} catch (InvalidDeleteDataEntityOperationException e) {
					// TODO handle exception
					e.printStackTrace();
				} catch (InvalidSaveDataEntityOperationException e) {
					// TODO handle exception
					e.printStackTrace();
				}
			}
			phoneContact.close();
		}
	}
	
	

	/**
	 * Scan the phone contacts and adds them to the alarm clock if missing
	 */
	protected void SyncPhoneToAlarmClock(Context i_Context) {
		ContactFactory contactFactory = new ContactFactory();
		Cursor phoneContacts; 
		String[] projection = new String[] { Contacts.LOOKUP_KEY };

		phoneContacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
		
		if (phoneContacts != null) {
			int lookUpKeyColumnIndex = phoneContacts.getColumnIndex(Contacts.LOOKUP_KEY); 
			if (phoneContacts.moveToFirst()) {
				do {
					ISingleContact currentContact = contactFactory.TryGetSingleContactByPhoneContactId(i_Context, phoneContacts.getString(lookUpKeyColumnIndex));
					if (currentContact == null) {
						currentContact = contactFactory.CreateSingleContact(phoneContacts.getString(lookUpKeyColumnIndex));
						try {
							currentContact.Save(getApplicationContext());
						} catch (InvalidSaveDataEntityOperationException ex) {
							//TODO handle exception
						}
					}
				} while (phoneContacts.moveToNext());
			}
		}
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d("onHandleIntent", "In service");
		while (true) {
			Log.d("onHandleIntent", "Entering syncronization");
			synchronized (this) {
				try {
					SyncContacts(this);
					wait(c_SleepInterval * 1000);
				} catch (InterruptedException ex) {
					//TODO handle exception
				}
				Log.d("onHandleIntent", "Getting out of syncronization");
			}
		}
	}
}
